package com.yuerlive.rainbow.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.RainbowApp;
import com.yuerlive.rainbow.entity.Gift;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.playlive.adapter.GiftAdapter;
import com.yuerlive.rainbow.module.playlive.adapter.GiftPagerAdapter;
import com.yuerlive.rainbow.module.recharge.RechargeActivity;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.ToastUtils;
import com.yuerlive.rainbow.utils.UserProxy;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GiftView extends RelativeLayout {
    private final String TAG = "GiftView";
    private final String TAB_MYCROPS = "mycrops";
    private final String TAB_GIFT = "gift";
    private List<View> giftViews = new ArrayList<>();
    private List<GiftAdapter> adapters = new ArrayList<>();
    int padding = DeviceUtils.dp2px(RainbowApp.getContext(), 12);
    @BindView(R.id.vp_gift)
    ViewPager vpGift;
    @BindView(R.id.tvMyCoinsCount)
    TextView tvMyCoinsCount;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.ll_coins)
    LinearLayout llCoins;
    @BindView(R.id.tvSendGift)
    TextView tvSendGift;
    @BindView(R.id.ivGift)
    ImageView ivGift;
    @BindView(R.id.rlSendGift)
    RelativeLayout rlSendGift;
    @BindView(R.id.bezRound)
    BezierRoundView bezRound;
    @BindView(R.id.rlbottom)
    RelativeLayout rlbottom;
    private List<Gift> mDatas;
    private List<View> mGiftPagers;
    private Context mContext;
    private Gift mChoosed;
    private User user;
    //  private View mChooseView;

    private boolean landScape;

    private int mgiftLastIndex = 0;
    private boolean isRenderSuccess = false;// 礼物没有加载成功的时候，不显示礼物View
    //  private List<FlowLayout> flowLayouts = new ArrayList<>();
    private List<View> bgs = new ArrayList<>();
    private SparseArray array;
    private MyHandler handler;
    private boolean isLoadGift = true;

    public GiftView(Context context) {
        super(context);
        initView(context);
    }

    public GiftView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView(context);
    }

    private void initView(Context context) {
        View.inflate(context, R.layout.layout_gift_view, this);
        ButterKnife.bind(this);
        user = UserProxy.getUser();
    }

    private int defaultHeight;


    /**
     * 设置礼物数据
     *
     * @param datas
     */
    public void setDatas(List<Gift> datas) {
        if (handler == null) {
            handler = new MyHandler(this);
        }
        this.mDatas = datas;
        createPagerAdapter();
        if (mDatas != null && mDatas.size() > 0) {
            isRenderSuccess = true;
        }
    }

    /**
     * 创建礼物页面
     */
    private void createPagerAdapter() {
        vpGift.removeAllViews();
        mGiftPagers = createGiftPagers();
        vpGift.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);

            }
        });
    }

    /**
     * 创建礼物页
     *
     * @return
     */
    private List<View> createGiftPagers() {
        giftViews.clear();
        //  flowLayouts.clear();
        adapters.clear();
        measure(-1, -1);
        int height = (getMeasuredHeight() - DeviceUtils.dp2px(mContext, 44)) / 2;
        bgs.clear();
        List<View> views = new ArrayList<>();
        array = sortData(mDatas);
        for (int i = 0; i < array.size(); i++) {
            List<Gift> gifts = (List<Gift>) array.get(i);
            View giftPage = LayoutInflater.from(mContext).inflate(R.layout.layout_pager_gift_flow, null);
            GridView gvGift = (GridView) giftPage.findViewById(R.id.gvGift);

            GiftAdapter adapter = new GiftAdapter(mContext, gifts, height);
            adapter.setItemClickListener(new GiftAdapter.ItemOnClickListener() {

                @Override
                public void itemClick(int position, View view) {
                    clearChoose();
                    view.setBackgroundResource(R.drawable.bg_retangle_01);
                    mChoosed = gifts.get(position);
                    view.requestFocus();
                    setDoubleHitBtn(false, 0);
                }

                @Override
                public void setView(View view) {
                    bgs.add(view);
                }
            });
            adapters.add(adapter);
            gvGift.setAdapter(adapter);
            views.add(giftPage);
        }
        //设置第一个礼物为默认礼物
        vpGift.setAdapter(new GiftPagerAdapter(views));
        vpGift.setOffscreenPageLimit(array.size());
        bezRound.attach2ViewPage(vpGift);

        setDefaultChoosed();
        return views;
    }

    /**
     * 设置默认选择第一个礼物
     */
    private void setDefaultChoosed() {
        clearChoose();
        if (array.size() == 0) return;
        ((List<Gift>) array.get(0)).get(0).setChoosed(1);
        if (adapters != null && adapters.size() > 0) {
            adapters.get(0).notifyDataSetChanged();
        }
        mChoosed = ((List<Gift>) array.get(0)).get(0);
    }

    private SparseArray<List<Gift>> sortData(List<Gift> datas) {
        SparseArray<List<Gift>> results = new SparseArray<>();

        int perCount = 8;
        int pageSize = datas.size() % perCount == 0 ? datas.size() / perCount :
                datas.size() / perCount + 1;
        for (int i = 0; i < pageSize; i++) {
            List<Gift> list = new ArrayList<>();
            for (int j = i * perCount; j < perCount + i * perCount && j < datas.size(); j++) {
                list.add(datas.get(j));
            }
            results.append(i, list);
        }
        return results;
    }

    /**
     * 创建礼物item
     *
     * @param gift
     * @return
     */
    private View createGiftViewItem(final Gift gift, int pos) {
        final View child = LayoutInflater.from(mContext).inflate(R.layout.layout_pager_gift_item, null);
        ImageView imgIcon = (ImageView) child.findViewById(R.id.imgIcon);
        ImageView ivGiftType = (ImageView) child.findViewById(R.id.ivGiftType);
        TextView tvGiftPrice = (TextView) child.findViewById(R.id.tvGiftPrice);
        RelativeLayout rlParent = (RelativeLayout) child.findViewById(R.id.rlParent);

        tvGiftPrice.setText(gift.getGiftRainbowSweet() + "");
        //   GlideUtil.load(mContext,"http://",imgIcon);
        imgIcon.setTag(gift.getId());
        child.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearChoose();
                rlParent.setBackgroundResource(R.drawable.bg_gift_selected);
                mChoosed = gift;
                //    mChooseView = rvGift;
                child.requestFocus();
            }
        });
        giftViews.add(child);
        return child;
    }


    @OnClick({R.id.tv_recharge, R.id.tvSendGift, R.id.rlbottom})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_recharge:
                Intent intent = new Intent(mContext, RechargeActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.tvSendGift:
                if (mGiftSendListener != null) {
                    if (user.getUserInfo().getRainbowSweet() < mChoosed.getGiftRainbowSweet() ||
                            user.getUserInfo().getFreezeSweet() + mChoosed.getGiftRainbowSweet() > user.getUserInfo().getRainbowSweet()) {
                        mGiftSendListener.showSnackBar(mContext.getResources().getString(R.string.balance_tips));
                    } else {

                    }

                    if (user.getUserInfo().getRainbowSweet()<mChoosed.getGiftRainbowSweet()){
                        mGiftSendListener.showSnackBar(mContext.getResources().getString(R.string.balance_tips));
                    }else if (user.getUserInfo().getFreezeSweet() +
                            mChoosed.getGiftRainbowSweet() > user.getUserInfo().getRainbowSweet()){
                        mGiftSendListener.showSnackBar(mContext.getResources().getString(R.string.balance_avaible_tips));
                    }else {
                        mChoosed.setFromNick(UserProxy.getUser().getUserInfo().getNickname());
                        mGiftSendListener.sendGift(mChoosed, vpGift.getCurrentItem());
                    }

                }
                break;
            case R.id.rlbottom:
                break;
        }
    }

    public void sendGiftSuccess(Gift gift) {
        int surplusSweet = Integer.parseInt(tvMyCoinsCount.getText().toString()) - gift.getGiftRainbowSweet();
        setCoinsCount(surplusSweet);
        user.getUserInfo().setRainbowSweet(surplusSweet);
        UserProxy.setUser(user);
        //连击礼物才显示连击倒计时
        if (gift.getType() == 2) {
            if ((System.currentTimeMillis() - gift.getStartTime()) / 1000 < 10 || gift.getStartTime() == 0) {
                //gift.setDoubleHitNum(gift.getDoubleHitNum() + 1);
            } else {
                gift.setDoubleHitNum(1);
            }
            resetCountDownTime();
            setDoubleHitBtn(true, 10);
            startTime = System.currentTimeMillis();
            gift.setStartTime(startTime);
        } else {
            gift.setDoubleHitNum(1);
        }

    }

    private long startTime = 0;

    public void setDoubleHitBtn(boolean click, int time) {
        if (click) {
            tvSendGift.setBackgroundResource(R.drawable.bg_rectangle_corner_solid_07);
            tvSendGift.setText("连击" + time);
            handler.sendEmptyMessageDelayed(0, 1000);
            isLoadGift = false;
        } else {
            tvSendGift.setBackgroundResource(R.drawable.bg_rectangle_corner_solid_06);
            tvSendGift.setText("赠送");
            resetCountDownTime();
            isLoadGift = true;
        }
    }

    /**
     * 重置倒计时时间为10秒
     */
    private void resetCountDownTime() {
        handler.setTime(10);
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 清除选中
     */
    private void clearChoose() {
        for (int i = 0; i < bgs.size(); i++) {
            ViewGroup parent = (ViewGroup) bgs.get(i).getParent();
            if (parent != null) {
                for (int j = 0; j < parent.getChildCount(); j++) {
                    parent.getChildAt(j).setBackgroundColor(mContext.getResources().getColor(R.color.black_percent_50));
                }
            }
        }
    }

    public interface SendGiftListener {
        void sendGift(Gift g, int giftType);

        void showSnackBar(String tips);
    }

    public void setSendGiftListner(SendGiftListener listener) {
        this.mGiftSendListener = listener;
    }

    private SendGiftListener mGiftSendListener;

    public void setCoinsCount(int count) {
        tvMyCoinsCount.setText("" + count);
    }

    public void hide() {
        if (getVisibility() == View.GONE) return;
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "translationY", 0, getHeight());
        animator.setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setVisibility(View.GONE);
                if (giftAnimationListener != null) {
                    giftAnimationListener.onAnimationState(1);
                }
            }
        });
        animator.start();
    }

    public void show() {
        if (getVisibility() == View.VISIBLE || !isRenderSuccess) return;

        measure(0, 0);

        if (defaultHeight == 0) {
            defaultHeight = getMeasuredHeight();
        }
        LayoutParams params = (LayoutParams) getLayoutParams();
        params.height = defaultHeight;
        setLayoutParams(params);
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "translationY", params.height, 0);
        animator.setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
                                 @Override
                                 public void onAnimationStart(Animator animation) {
                                     super.onAnimationStart(animation);
                                     setVisibility(View.VISIBLE);
                                 }
                             }
        );
        animator.start();
        setDoubleHitBtn(false, 0);
    }

    public void setLandScape(boolean landScape) {
        this.landScape = landScape;
    }

    private GiftAnimationListener giftAnimationListener;

    public void setGiftAnimationListener(GiftAnimationListener listener) {
        this.giftAnimationListener = listener;
    }

    public interface GiftAnimationListener {
        void onAnimationState(int state);   //0,开始 1 结束

    }

    public static class MyHandler extends Handler {
        private int time = 10;
        private WeakReference<GiftView> weakReference;

        public MyHandler(GiftView giftView) {
            weakReference = new WeakReference<GiftView>(giftView);
        }

        public void setTime(int time) {
            this.time = time;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference.get() != null) {
                time--;
                if (time == 0) {
                    weakReference.get().setDoubleHitBtn(false, time);
                } else {
                    weakReference.get().setDoubleHitBtn(true, time);
                }
            }
        }
    }
}
